import logger from '@common/logger';
import { SCENES_VALUE } from '@constants/platformTypes';
/**
 * 处理劵
 * @param {Array} coupons 劵数组
 */
export const dealCoupons = (coupons) => {
    const unused = []; // 使用
    const used = []; // 已使用
    const expire = []; // 已过期
    coupons.map(item => {
        if (item.status === 0) {
            unused.push(item);
        }
    });
};

/**
 * 根据规则返回首页展示的卡片信息
 * 规则：
 * 1.优先展示和门店相同的卡
 * 2.没有门店信息：会员卡余额 > 会员积分 > 会员折扣 > 上次消费 > 随机
 * @param {Array} cardList 卡数据列表
 */
export const getShowCard = (cardList=[], storeId) => {
    // if (cardList.length === 1) {
    //     return cardList[0];
    // }
    const _list = storeCardList(cardList, storeId);
    const len = _list.length;
    if (len === 0) {
        return false;
    }
    // 只有一条数据，直接返回，大部分情况
    if (len === 1) {
        return _list[0];
    }
    let optimal = _list[0];
    for (let i = 1; i < len; i++) {
        optimal = compareVal(optimal, _list[i]);
    }
    return optimal;
};

/**
 * 根据规则返回首页展示的卡片信息
 * 规则：
 * 0.最先展示品牌的卡
 * 1.优先展示和门店相同的卡
 * 2.没有门店信息：会员卡余额 > 会员积分 > 会员折扣 > 上次消费 > 随机
 * @param {Array} cardList 卡数据列表
 */
export const getSortGroupCardResult = (cardList=[], storeId) => {
    const storeList = storeCardList(cardList, storeId);
    const list = sortArray(storeList).filter(item => `${item.groupId}` !== '0');
    const { brandList, otherList } = getBrandCardList(list);
    return [...brandList, ...otherList];
};

const sortArray = (arr) => {
    return arr.sort((one, two) => {
        if (one.balance > two.balance) {
            return -1;
        } else if (one.balance === two.balance) {
            // 校验折扣
            if (one.disCount < two.disCount) {
                return -1;
            } else if (one.disCount === two.disCount) {
                return -1;
            } else {
                return 1;
            }
        } else {
            return 1;
        }
    });
};

/**
 * 获取品牌卡
 * @param {Array} groups 卡列表
 */
const getBrandCardList = (groups) => {
    const brandList = [];
    const otherList = [];
    groups.forEach(item => {
        const { owner } = item.grade;
        if (owner && `${owner}` === '0') {
            brandList.push(item);
        } else {
            otherList.push(item);
        }
    });
    return {
        brandList,
        otherList,
    };
};


/**
 * 返回当前门店的会员卡
 * @param {Array} list 会员卡数组
 * @param {Number | String} storeId 门店id
 */
const storeCardList = (list, storeId) => {
    if (!storeId) {
        if (list.length > 1) {
            return list.filter(item => `${item.groupId}` !== '0');
        }
        return list;
    }
    let result = [];
    for (let i = 0; i < list.length; i++) {
        const stores = getStoresIds(list[i].stores || []);
        if (stores.indexOf(parseInt(storeId)) > -1) {
            result.push(list[i]);
        }
    }
    return result;
};

/**
 * 比较两个对象，返回最优结果
 *  GV: 0
    LGV: 0
    balance: 150
    brandId: "33"
    created: 1544696844612
    disCount: 10
    gradeId: "1741"
    gradeName: "普通会员"
    groupId: "0"
    integral: 0
    memberId: "2712626"
    modified: 1547622963000
 * @param {Object} one 对象1
 * @param {Object} two 对象2
 */
const compareVal = (one, two) => {
    // 校验余额
    if (one.balance > two.balance) {
        return one;
    } else if (one.balance === two.balance) {
        // 校验折扣
        if (one.disCount < two.disCount) {
            return one;
        } else if (one.disCount === two.disCount) {
            return one;
        } else {
            return two;
        }
    } else {
        return two;
    }
};

/**
 * 根据会员卡ID获取会员卡详情
 * @param {Array} cardList 会员卡数组
 * @param {String} cardId 会员卡ID
 */
export const getCardInfoById = (cardList=[], cardId) => {
    let result = {};
    for (let i = 0; i < cardList.length; i++) {
        const item = cardList[i];
        if (item.gradeId === cardId) {
            result = item;
            break;
        }
    }
    return result;
};

/**
 * 获取会员卡相关的所有门店id
 * @param {Array} array 包含门店id的数组
 */
export const getStoresIds = (array=[]) => {
    return array.map(item => parseInt(item.storeId));
};

/**
 * 获取选中的卡
 * @param {Array} arr 卡列表数组
 * @param {Number|String} id 选中的 id
 */
export const getSelectItemCard = (arr, id) => {
    return arr.filter(item => item.gradeId === id)[0] || null;
};

/**
 * 获取场景值
 * @param {Array} scenesList 场景值数组
 */
export const getScenesValue = (scenesList) => {
    return Array.from(new Set(scenesList.map(item => SCENES_VALUE[item] || ''))).join('、');
};

/**
 * 获取优惠券使用的情况数据
 * @param {Array} coupons 优惠券信息列表
 * @param {Object} info 营销SDK返回的使用情况
 */
export const getCouponsList = (coupons, info) => {};

/**
 * 获取红包使用情况
 * @param {Array} coupons 优惠券信息列表
 * @param {Object} info 营销SDK返回的红包使用情况
 */
export const getRedPacketList = (coupons, info) => {};

/**
 * 获取门店可用会员卡
 * @param {Array} list 会员卡列表
 */
export const getAviableCards = (list=[], storeId) => {
    const id = storeId ? storeId : '';
    if (!id) {
        return (list || []).filter(item => `${item.groupId}` !== '0' || item.stores.length > 0);
    }
    const result = [];
    for (let i = 0; i < list.length; i++) {
        const item = list[i];
        if (item.stores.filter(temp => `${temp.storeId}` === `${id}`).length > 0) {
            result.push(item);
        }
    }
    return sortArray(result);
};

/**
 * 获取商城会员卡
 * @param {Array} list 会员卡列表
 */
export const getShopCard = (list=[]) => {
    let shopCard = {};
    for (let i = 0; i < list.length; i++) {
        const item = list[i];
        if (item.businessTypes && item.businessTypes.indexOf('emall') > -1) {
            shopCard = {
                ...item,
            };
        }
    }
    return shopCard;
};

/**
 * 对会员卡进行排序
 * @param {Array} cardList 卡列表
 * @param {Number} storeId 门店id
 */
export const sortMemberCard = (cardList=[], storeId) => {
    const available = [];
    const disabled = [];
    const len = cardList ? cardList.length : 0;
    const normalCard = (cardList || []).filter(item => `${item.groupId}` === '0')[0] || {stores: []};
    const isDel = len > 1 && normalCard.stores.length < 1;
    for (let i = 0; i < cardList.length; i++) {
        const item = cardList[i];
        const flag = item.stores.filter(i => `${i.storeId}` === `${storeId}`).length === 0;
        if (`${item.groupId}` === '0' && isDel) {
            continue;
        }
        if (flag && storeId) {
            disabled.push({
                ...item,
                isDisable: true,
            });
        } else {
            available.push({
                ...item,
                isDisable: false,
            });
        }
    }
    const { brandList, otherList } = getBrandCardList(available);
    return [...sortArray(brandList), ...sortArray(otherList), ...sortArray(disabled)];
};

/**
 * 处理实体卡信息
 * @param {Object} info
 */
export const drawEntityCardInfo = (info) => {
    return {
        name: info.gradeName,
        cardNumber: info.cardNumber,
        discount: info.gradeDiscount,
        balance: info.balance,
        deposit: info.depositBalance,
        mobile: info.mobile,
        groupId: info.groupId,
    };
};

/**
 * 处理积分商城返回数据为可用数据，剔除无效信息
 * @param {Array} list 积分商城数据
 */
export const dealIntegralShopData = (list) => {
    const result = [];
    list.forEach(item => {
        const { activitySalesTime, integralExchangeSetting, coupon } = item;
        result.push({
            name: item.name,
            price: integralExchangeSetting.integralCnt,
            max: integralExchangeSetting.memberExchangeMax,
            id: item.activityId,
            type: activitySalesTime.type,
            isForever: activitySalesTime.type === 'forever',
            startDate: activitySalesTime.startDate,
            endDate: activitySalesTime.endDate,
            weekdays: activitySalesTime.weekdays,
            timeRanges: activitySalesTime.timeRanges,
            coupon: {
                name: coupon.ext.name,
                mode: coupon.ext.type,
                scenes: coupon.ext.scenes,
                price: coupon.ext.price,
                quota: coupon.ext.quota,
                allStore: coupon.allStore,
                stores: coupon.stores,
                type: coupon.ext.salesTime.type,
                startDate: coupon.ext.salesTime.startDate > 0 ? coupon.ext.salesTime.startDate : '',
                endDate: coupon.ext.salesTime.endDate > 0 ? coupon.ext.salesTime.endDate : '',
                isForever: coupon.ext.salesTime.type === 'forever',
                weekdays: coupon.ext.salesTime.weekdays,
                timeRanges: coupon.ext.salesTime.timeRanges,
                day: coupon.ext.day,
                product: coupon.ext.product || null,
                overlaySameCategory: coupon.ext.overlaySameCategory,
            },
        });
    });
    return result;
};
